package com.bjpowernode.jdbc;

import utils.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;

public class JDBCTest13 {
    public static void main(String[] args) {
        //演示悲观锁机制
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            //获取连接
            conn = DBUtil.getConnection();
            //关闭自动提交
            conn.setAutoCommit(false);

            //执行sql语句
            String sql = "select empno,ename,job from emp where job = ? for update ";
            ps = conn.prepareStatement(sql);
            ps.setString(1, "MANAGER");

            //处理查询结果集
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getInt("empno") + "," + rs.getString("ename") + "," + rs.getString("job"));
            }

            //提交事务
            conn.commit();
        } catch (SQLException e) {
            //事务回滚
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        } finally {
            //释放资源
            DBUtil.close(conn, ps, rs);
        }
    }
}
